<?php
/**
 * <pre>
 * DiabloStudios.Board v1.0
 * 
 * Manage the forums
 * </pre>
 * 
 * @copyright	(c) 2010 DiabloStudios
 * @license		GNU Affero GPL v3 or newer
 * @package		PHP-Fusion
 * @subpackage	DiabloStudios.Board
 * @link		http://diablostudios.pl
 * @version     $Id: forums.php 1 2011-03-20 11:56:30Z Bartek $
 */

require_once(DSB_LANGDIR."admin_forums.php");
require_once(DSB_DIR."includes/admin_functions.php");

if ($dsb->input['action'])
{
    $action = $dsb->input['action'];
    $desc = $locale[$dsb->input['action'].'_forums_desc'];
}
else
{
    $action = "";
    if (!$dsb->input['fid'])
    {
        $desc = $locale['forums_desc'];
    }
    else
    {
        $desc = $locale['preview_forums_desc'];
    }
}
if($dsb->input['fid'] && ($dsb->input['action'] == "management" || $dsb->input['action'] == "edit" || $dsb->input['action'] == "copy" || !$dsb->input['action']))
{
    echo '<div class="nav_tabs">	<ul>';
    echo '		<li class="tbl-border first '.(!$action && $dsb->input['fid'] ? 'active tbl2' : 'tbl1').'"><a href="index.php'.$aidlink.'&amp;module=forums&amp;fid='.$dsb->input['fid'].'">'.$locale['preview_forums'].'</a></li>';
    echo '		<li class="tbl-border '.($action == 'add' ? 'active tbl2' : 'tbl1').'"><a href="index.php'.$aidlink.'&amp;module=forums&amp;action=add&amp;pid='.$dsb->input['fid'].'">'.$locale['add_subforums'].'</a></li>';
    echo '		<li class="tbl-border '.($action == 'edit' ? 'active tbl2' : 'tbl1').'"><a href="index.php'.$aidlink.'&amp;module=forums&amp;action=edit&amp;fid='.$dsb->input['fid'].'">'.$locale['edit_forums'].'</a></li>';
    echo '		<li class="tbl-border last '.($action == 'copy' ? 'active tbl2' : 'tbl1').'"><a href="index.php'.$aidlink.'&amp;module=forums&amp;action=copy&amp;fid='.$dsb->input['fid'].'">'.$locale['copy_forums'].'</a></li>';
    echo '	</ul>';
    echo '  <br style="clear: both" />';
    echo '	<div class="tab_description tbl2 tbl-border">'.$desc.'</div>';
    echo '</div>'; 
}
else
{
    echo '<div class="nav_tabs">	<ul>';
    echo '		<li class="tbl-border first '.(!$action ? 'active tbl2' : 'tbl1').'"><a href="index.php'.$aidlink.'&amp;module=forums">'.$locale['forums'].'</a></li>';
    echo '		<li class="tbl-border last '.($action == 'add' ? 'active tbl2' : 'tbl1').'"><a href="index.php'.$aidlink.'&amp;module=forums&amp;action=add">'.$locale['add_forums'].'</a></li>';
    echo '	</ul>';
    echo '  <br style="clear: both" />';
    echo '	<div class="tab_description tbl2 tbl-border">'.$desc.'</div>';
    echo '</div>';
}

add_to_head("<script src=\"".DSB_DIR."js/jquery.ui.core.js\" type=\"text/javascript\"></script>");
add_to_head("<script src=\"".DSB_DIR."js/jquery.ui.widget.js\" type=\"text/javascript\"></script>");
add_to_head("<script src=\"".DSB_DIR."js/jquery.ui.mouse.js\" type=\"text/javascript\"></script>");
add_to_head("<script src=\"".DSB_DIR."js/jquery.ui.sortable.js\" type=\"text/javascript\"></script>");

if($dsb->input['action'] == "copy")
{

	if($dsb->request_method == "post")
	{
		$from = intval($dsb->input['from']);
		$to = intval($dsb->input['to']);
	
		// Find the source forum
		$query = $db->simple_select("forums", '*', "fid='{$from}'");
		$from_forum = $db->fetch_array($query);
		if(!$db->num_rows($query))
		{
			$errors[] = $locale['error_invalid_source_forum'];
		}
	
		if($to == -1)
		{
			// Create a new forum
			if(empty($dsb->input['title']))
			{
				$errors[] = $locale['error_new_forum_needs_name'];
			}
			
			if($dsb->input['pid'] == -1 && $dsb->input['type'] == 'f')
			{
				$errors[] = $locale['error_forum_noparent'];
			}
	
			if(!$errors)
			{
				$new_forum = $from_forum;
				unset($new_forum['fid'], $new_forum['threads'], $new_forum['posts'], $new_forum['lastpost'], $new_forum['lastposter'], $new_forum['lastposteruid'], $new_forum['lastposttid'], $new_forum['lastpostsubject'], $new_forum['unapprovedthreads'], $new_forum['unapprovedposts']);
				$new_forum['name'] = dsb_escape_string($dsb->input['title']);
				$new_forum['description'] = dsb_escape_string($dsb->input['description']);
				$new_forum['type'] = dsb_escape_string($dsb->input['type']);
				$new_forum['pid'] = intval($dsb->input['pid']);
				$new_forum['rulestitle'] = dsb_escape_string($new_forum['rulestitle']);
				$new_forum['rules'] = dsb_escape_string($new_forum['rules']);
				$new_forum['parentlist'] = '';
						
				$to = $db->insert_query("forums", $new_forum);
		
				// Generate parent list
				$parentlist = make_parent_list($to);
				$updatearray = array(
					'parentlist' => $parentlist
				);
				$db->update_query("forums", $updatearray, "fid='{$to}'");
			}
		}
		elseif($dsb->input['copyforumsettings'] == 1)
		{
			// Copy settings to existing forum
			$query = $db->simple_select("forums", '*', "fid='{$to}'");
			$to_forum = $db->fetch_array($query);
			if(!$db->num_rows($query))
			{
				$errors[] = $locale['error_invalid_destination_forum'];
			}
			
			if(!$errors)
			{
				$new_forum = $from_forum;
				unset($new_forum['fid'], $new_forum['threads'], $new_forum['posts'], $new_forum['lastpost'], $new_forum['lastposter'], $new_forum['lastposteruid'], $new_forum['lastposttid'], $new_forum['lastpostsubject'], $new_forum['unapprovedthreads'], $new_forum['unapprovedposts']);
				$new_forum['name'] = dsb_escape_string($to_forum['name']);
				$new_forum['description'] = dsb_escape_string($to_forum['description']);
				$new_forum['pid'] = dsb_escape_string($to_forum['pid']);
				$new_forum['parentlist'] = dsb_escape_string($to_forum['parentlist']);
				$new_forum['rulestitle'] = dsb_escape_string($new_forum['rulestitle']);
				$new_forum['rules'] = dsb_escape_string($new_forum['rules']);
				
				$db->update_query("forums", $new_forum, "fid='{$to}'");
			}
		}
		
		if(!$errors)
		{
			// Copy permissions
			if(is_array($dsb->input['copygroups']) && count($dsb->input['copygroups'] > 0))
			{
				foreach($dsb->input['copygroups'] as $gid)
				{
					$groups[] = intval($gid);
				}
				$groups = implode(',', $groups);
				$query = $db->simple_select("forumpermissions", '*', "fid='{$from}' AND gid IN ({$groups})");
				$db->delete_query("forumpermissions", "fid='{$to}' AND gid IN ({$groups})", 1);
				while($permissions = $db->fetch_array($query))
				{
					unset($permissions['pid']);
					$permissions['fid'] = $to;
		
					$db->insert_query("forumpermissions", $permissions);
				}
				
				// Log admin action
				log_admin_action($from, $from_forum['name'], $to, $new_forum['name'], $groups);
			}
			else
			{
				// Log admin action (no group permissions)
				log_admin_action($from, $from_forum['name'], $to, $new_forum['name']);
			}
			$cache->update_forums();
			$cache->update_forumpermissions();
			
			$plugins->run_hooks("admin_forum_management_copy_commit");
		
			flash_message($locale['success_forum_copied'], 'success');
			admin_redirect("index.php?module=forum-management&action=edit&fid={$to}");
		}
	}
	
	//$page->add_breadcrumb_item($locale['copy_forum']);
	//$page->output_header($locale['copy_forum']);	
	//$page->output_nav_tabs($sub_tabs, 'copy_forum');
	
	$form = new Form("index.php{$aidlink}&amp;module=forums&amp;action=copy", "post");

	if($errors)
	{
		output_inline_error($errors);
		$copy_data = $dsb->input;
	}
	else
	{		
		$copy_data['type'] = "f";
		$copy_data['title'] = "";
		$copy_data['description'] = "";
		
		if(!$dsb->input['pid'])
		{
			$copy_data['pid'] = "-1";
		}
		else
		{
			$copy_data['pid'] = intval($dsb->input['pid']);
		}
		$copy_data['disporder'] = "1";
		$copy_data['from'] = $dsb->input['fid'];
		$copy_data['copyforumsettings'] = 0;
		$copy_data['pid'] = 0;
	}
	
	$types = array(
		'f' => $locale['forum'],
		'c' => $locale['category']
	);
	
	$create_a_options_f = array(
		'id' => 'forum'
	);
	
	$create_a_options_c = array(
		'id' => 'category'
	);
	
	if($copy_data['type'] == "f")
	{
		$create_a_options_f['checked'] = true;
	}
	else
	{
		$create_a_options_c['checked'] = true;
	}
	
	$usergroups = array();
	
	$query = dbquery("SELECT gid,title FROM ".DB_DSB_USERGROUPS." WHERE gid != '1' ORDER BY title");
	while($usergroup = dbarray($query))
	{
		$usergroups[$usergroup['gid']] = $usergroup['title'];
	}
	echo "<br />";
	$form_container = new FormContainer($locale['copy_forum'],'form_container');
	$form_container->output_row($locale['source_forum']." <em>*</em>", $locale['source_forum_desc'], $form->generate_forum_select('from', $copy_data['from'], array('id' => 'from')), 'from');
	$form_container->output_row($locale['destination_forum']." <em>*</em>", $locale['destination_forum_desc'], $form->generate_forum_select('to', $copy_data['to'], array('id' => 'to', 'main_option' => $locale['copy_to_new_forum'])), 'to');
	$form_container->output_row($locale['copy_settings_and_properties'], $locale['copy_settings_and_properties_desc'], $form->generate_yes_no_radio('copyforumsettings', $copy_data['copyforumsettings']));
	$form_container->output_row($locale['copy_user_group_permissions'], $locale['copy_user_group_permissions_desc'], $form->generate_select_box('copygroups[]', $usergroups, $dsb->input['copygroups'], array('id' => 'copygroups', 'multiple' => true, 'size' => 5)), 'copygroups');
	
	$form_container->end();

	$form_container = new FormContainer($locale['new_forum_settings'],'form_container');
	$form_container->output_row($locale['create_a'], $locale['create_a_desc'], $form->generate_radio_button('type', 'f', $locale['forum'], $create_a_options_f)."<br />\n".$form->generate_radio_button('type', 'c', $locale['category'], $create_a_options_c));
	$form_container->output_row($locale['title']." <em>*</em>", "", $form->generate_text_box('title', $copy_data['title'], array('id' => 'title')), 'title');
	$form_container->output_row($locale['description'], "", $form->generate_text_area('description', $copy_data['description'], array('id' => 'description')), 'description');
	$form_container->output_row($locale['parent_forum']." <em>*</em>", $locale['parent_forum_desc'], $form->generate_forum_select('pid', $copy_data['pid'], array('id' => 'pid', 'main_option' => $locale['none'])), 'pid');
	
	$form_container->end();
	
	$buttons[] = $form->generate_submit_button($locale['copy_forum'],array('class' => 'button'));
	$form->output_submit_wrapper($buttons);
	$form->end();

}

if($dsb->input['action'] == "add")
{
	
	if($dsb->request_method == "post")
	{
		if(!trim($dsb->input['title']))
		{
			$errors[] = $locale['error_missing_title'];
		}
		
		$pid = intval($dsb->input['pid']);
		$type = $dsb->input['type'];
		
		if($pid <= 0 && $type == "f")
		{
			$errors[] = $locale['error_no_parent'];
		}
		
		if(!$errors)
		{
			if($pid < 0)
			{
				$pid = 0;
			}
            if ($type == "c") { $fc = "0"; } else { $fc = $pid; }
             $insert_array = array(
                "forum_cat" => intval($fc),
                "forum_name" => dsb_escape_string($dsb->input['title']),
                "forum_order" => intval($dsb->input['disporder']),
                "forum_description" => dsb_escape_string($dsb->input['description']),
                "forum_access" => "101",
            );
            $fid = dbinsert(DB_FORUMS, $insert_array);
 
			$insert_array2 = array(
                "fid" => $fid,
				"linkto" => dsb_escape_string($dsb->input['linkto']),
				"type" => dsb_escape_string($type),
				"pid" => $pid,
				"parentlist" => '',
				"active" => intval($dsb->input['active']),
				"open" => intval($dsb->input['open']),
				"allowhtml" => intval($dsb->input['allowhtml']),
				"allowmycode" => intval($dsb->input['allowmycode']),
				"allowsmilies" => intval($dsb->input['allowsmilies']),
				"allowimgcode" => intval($dsb->input['allowimgcode']),
				"allowvideocode" => intval($dsb->input['allowvideocode']),
				"allowpicons" => intval($dsb->input['allowpicons']),
				"allowtratings" => intval($dsb->input['allowtratings']),
				"usepostcounts" => intval($dsb->input['usepostcounts']),
				"showinjump" => intval($dsb->input['showinjump']),
				"modposts" => intval($dsb->input['modposts']),
				"modthreads" => intval($dsb->input['modthreads']),
				"mod_edit_posts" => intval($dsb->input['mod_edit_posts']),
				"modattachments" => intval($dsb->input['modattachments']),
				"defaultdatecut" => intval($dsb->input['defaultdatecut']),
				"defaultsortby" => dsb_escape_string($dsb->input['defaultsortby']),
				"defaultsortorder" => dsb_escape_string($dsb->input['defaultsortorder']),
			);
			$fid2 = dbinsert(DB_DSB_FORUMS, $insert_array2);
			
    		$parentlist = make_parent_list($fid);
            dbquery("UPDATE ".DB_DSB_FORUMS." SET parentlist={$parentlist} WHERE fid='$fid'");
			
			$inherit = $dsb->input['default_permissions'];
			
			foreach($dsb->input as $id => $permission)
			{
				if(strpos($id, 'fields_') === false)
				{
					continue;
				}
				
				list(, $gid) = explode('fields_', $id);
				
				// If it isn't an array then it came from the javascript form
				if(!is_array($permission))
				{
					$permission = explode(',', $permission);
					$permission = array_flip($permission);
					foreach($permission as $name => $value)
					{
						$permission[$name] = 1;
					}
				}
				
				foreach(array('canview','canpostthreads','canpostreplys','canpostpolls') as $name)
				{
					if(in_array($name, $permission)  || $permission[$name])
					{
						$permissions[$name][$gid] = 1;
					}
					else
					{
						$permissions[$name][$gid] = 0;
					}
				}
			}
			
			$cache->update_forums();
			
			$canview = $permissions['canview'];
			$canpostthreads = $permissions['canpostthreads'];
			$canpostpolls = $permissions['canpostpolls'];
			$canpostattachments = $permissions['canpostattachments'];
			$canpostreplies = $permissions['canpostreplys'];
			//save_quick_perms($fid);
			
		
			// Log admin action
			//log_admin_action($fid, $insert_array['name']);
			
			//flash_message($locale['success_forum_added'], 'success');
			redirect("index.php{$aidlink}&amp;module=forums");
		}
	}
	
    /*
	$page->add_breadcrumb_item($locale['add_forum']);
	$page->output_header($locale['add_forum']);
	$page->output_nav_tabs($sub_tabs, 'add_forum');
	*/
	$form = new Form("index.php{$aidlink}&amp;module=forums&amp;action=add", "post");

	if($errors)
	{
		echo output_inline_error($errors);
		$forum_data = $dsb->input;    
	}
	else
	{
        $forum_data['type'] = "f";
		$forum_data['title'] = "";
		$forum_data['description'] = "";
		
		if(!$dsb->input['pid'])
		{
			$forum_data['pid'] = "-1";
		}
		else
		{
			$forum_data['pid'] = intval($dsb->input['pid']);
		}
		$forum_data['disporder'] = "1";
		$forum_data['linkto'] = "";
		$forum_data['password'] = "";
		$forum_data['active'] = 1;
		$forum_data['open'] = 1;
		$forum_data['modposts'] = "";
		$forum_data['modthreads'] = "";
		$forum_data['modattachments'] = "";
		$forum_data['mod_edit_posts'] = "";
		$forum_data['defaultdatecut'] = "";
		$forum_data['defaultsortby'] = "";
		$forum_data['defaultsortorder'] = "";
		$forum_data['allowhtml'] = "";
		$forum_data['allowmycode'] = 1;
		$forum_data['allowsmilies'] = 1;
		$forum_data['allowimgcode'] = 1;
		$forum_data['allowvideocode'] = 1;
		$forum_data['allowpicons'] = 1;
		$forum_data['allowtratings'] = 1;
		$forum_data['showinjump'] = 1;
		$forum_data['usepostcounts'] = 1;
	}
	
	$types = array(
		'f' => $locale['forum'],
		'c' => $locale['category']
	);
	
	$create_a_options_f = array(
		'id' => 'forum'
	);
	
	$create_a_options_c = array(
		'id' => 'category'
	);
	
	if($forum_data['type'] == "f")
	{
		$create_a_options_f['checked'] = true;
	}
	else
	{
		$create_a_options_c['checked'] = true;
	}
    echo "<br />";
	$form_container = new FormContainer($locale['add_forum'], 'form_container');
	$form_container->output_row($locale['create_a'], $locale['create_a_desc'], $form->generate_radio_button('type', 'f', $locale['forum'], $create_a_options_f)."<br />\n".$form->generate_radio_button('type', 'c', $locale['category'], $create_a_options_c));
	$form_container->output_row($locale['title']." <em>*</em>", "", $form->generate_text_box('title', $forum_data['title'], array('id' => 'title')), 'title');
	$form_container->output_row($locale['description'], "", $form->generate_text_area('description', $forum_data['forum_description'], array('id' => 'description')), 'description');
	$form_container->output_row($locale['parent_forum']." <em>*</em>", $locale['parent_forum_desc'], $form->generate_forum_select('pid', $forum_data['pid'], array('id' => 'pid', 'main_option' => $locale['none'])), 'pid');
	$form_container->output_row($locale['display_order'], "", $form->generate_text_box('disporder', $forum_data['disporder'], array('id' => 'disporder')), 'disporder');
	$form_container->end();
	

    

	
	echo "<div><div><div><div><div><div><div>\n";
	$form_container = new FormContainer($locale['additional_forum_options'], 'form_container');
	$form_container->output_row($locale['forum_link'], $locale['forum_link_desc'], $form->generate_text_box('linkto', $forum_data['linkto'], array('id' => 'linkto')), 'linkto');

	$access_options = array(
		$form->generate_check_box('active', 1, $locale['forum_is_active']."<br />\n<small>{$locale['forum_is_active_desc']}</small>", array('checked' => $forum_data['active'], 'id' => 'active')),
		$form->generate_check_box('open', 1, $locale['forum_is_open']."<br />\n<small>{$locale['forum_is_open_desc']}</small>", array('checked' => $forum_data['open'], 'id' => 'open'))
	);
	
	$form_container->output_row($locale['access_options'], "", "<div class=\"forum_settings_bit\">".implode("</div><div class=\"forum_settings_bit\">", $access_options)."</div>");
	
	$moderator_options = array(
		$form->generate_check_box('modposts', 1, $locale['mod_new_posts'], array('checked' => $forum_data['modposts'], 'id' => 'modposts')),
		$form->generate_check_box('modthreads', 1, $locale['mod_new_threads'], array('checked' => $forum_data['modthreads'], 'id' => 'modthreads')),
		$form->generate_check_box('modattachments', 1, $locale['mod_new_attachments'], array('checked' => $forum_data['modattachments'], 'id' => 'modattachments')),
		$form->generate_check_box('mod_edit_posts', 1, $locale['mod_after_edit'], array('checked' => $forum_data['mod_edit_posts'], 'id' => 'mod_edit_posts'))
	);
	
	$form_container->output_row($locale['moderation_options'], "", "<div class=\"forum_settings_bit\">".implode("</div><div class=\"forum_settings_bit\">", $moderator_options)."</div>");
	
	$default_date_cut = array(
		0 => $locale['board_default'],
		1 => $locale['datelimit_1day'],
		5 => $locale['datelimit_5days'],
		10 => $locale['datelimit_10days'],
		20 => $locale['datelimit_20days'],
		50 => $locale['datelimit_50days'],
		75 => $locale['datelimit_75days'],
		100 => $locale['datelimit_100days'],
		365 => $locale['datelimit_lastyear'],
		9999 => $locale['datelimit_beginning'],
	);
	
	$default_sort_by = array(
		"" => $locale['board_default'],
		"subject" => $locale['sort_by_subject'],
		"lastpost" => $locale['sort_by_lastpost'],
		"starter" => $locale['sort_by_starter'],
		"started" => $locale['sort_by_started'],
		"rating" => $locale['sort_by_rating'],
		"replies" => $locale['sort_by_replies'],
		"views" => $locale['sort_by_views'],
	);
	
	$default_sort_order = array(
		"" => $locale['board_default'],
		"asc" => $locale['sort_order_asc'],
		"desc" => $locale['sort_order_desc'],
	);
	
	$view_options = array(
		$locale['default_date_cut']."<br />\n".$form->generate_select_box('defaultdatecut', $default_date_cut, $forum_data['defaultdatecut'], array('checked' => $forum_data['defaultdatecut'], 'id' => 'defaultdatecut')),
		$locale['default_sort_by']."<br />\n".$form->generate_select_box('defaultsortby', $default_sort_by, $forum_data['defaultsortby'], array('checked' => $forum_data['defaultsortby'], 'id' => 'defaultsortby')),
		$locale['default_sort_order']."<br />\n".$form->generate_select_box('defaultsortorder', $default_sort_order, $forum_data['defaultsortorder'], array('checked' => $forum_data['defaultsortorder'], 'id' => 'defaultsortorder')),
	);
	
	$form_container->output_row($locale['default_view_options'], "", "<div class=\"forum_settings_bit\">".implode("</div><div class=\"forum_settings_bit\">", $view_options)."</div>");
	
	$misc_options = array(
		$form->generate_check_box('allowhtml', 1, $locale['allow_html'], array('checked' => $forum_data['allowhtml'], 'id' => 'allowhtml')),
		$form->generate_check_box('allowmycode', 1, $locale['allow_mycode'], array('checked' => $forum_data['allowmycode'], 'id' => 'allowmycode')),
		$form->generate_check_box('allowsmilies', 1, $locale['allow_smilies'], array('checked' => $forum_data['allowsmilies'], 'id' => 'allowsmilies')),
		$form->generate_check_box('allowimgcode', 1, $locale['allow_img_code'], array('checked' => $forum_data['allowimgcode'], 'id' => 'allowimgcode')),
		$form->generate_check_box('allowvideocode', 1, $locale['allow_video_code'], array('checked' => $forum_data['allowvideocode'], 'id' => 'allowvideocode')),
		$form->generate_check_box('allowpicons', 1, $locale['allow_post_icons'], array('checked' => $forum_data['allowpicons'], 'id' => 'allowpicons')),
		$form->generate_check_box('allowtratings', 1, $locale['allow_thread_ratings'], array('checked' => $forum_data['allowtratings'], 'id' => 'allowtratings')),
		$form->generate_check_box('showinjump', 1, $locale['show_forum_jump'], array('checked' => $forum_data['showinjump'], 'id' => 'showinjump')),
		$form->generate_check_box('usepostcounts', 1, $locale['use_postcounts'], array('checked' => $forum_data['usepostcounts'], 'id' => 'usepostcounts'))
	);
	
	$form_container->output_row($locale['misc_options'], "", "<div class=\"forum_settings_bit\">".implode("</div><div class=\"forum_settings_bit\">", $misc_options)."</div>");
	$form_container->end();

    
	$query = dbquery("SELECT * FROM ".DB_DSB_USERGROUPS." ORDER BY gid ASC");
	while($usergroup = dbarray($query))
	{
		$usergroups[$usergroup['gid']] = $usergroup;
	}
	
	$cached_forum_perms = $cache->read("forumpermissions");
	$field_list = array(
		'canview' => $locale['permissions_canview'],
		'canpostthreads' => $locale['permissions_canpostthreads'],
		'canpostreplys' => $locale['permissions_canpostreplys'],
		'canpostpolls' => $locale['permissions_canpostpolls'],
	);
	
	$field_list2 = array(
		'canview' => $locale['perm_drag_canview'],
		'canpostthreads' => $locale['perm_drag_canpostthreads'],
		'canpostreplys' => $locale['perm_drag_canpostreplys'],
		'canpostpolls' => $locale['perm_drag_canpostpolls'],
	);
	
	$ids = array();

	$form_container = new FormContainer($locale['forum_permissions'],'form_container');
	$form_container->output_row_header($locale['permissions_group'], array("class" => "align_center", 'style' => 'width: 40%'));
	$form_container->output_row_header($locale['overview_allowed_actions'], array("class" => "align_center"));
	$form_container->output_row_header($locale['overview_disallowed_actions'], array("class" => "align_center"));
	
	if($dsb->request_method == "post")
	{
		foreach($usergroups as $usergroup)
		{
			if(isset($dsb->input['fields_'.$usergroup['gid']]))
			{
				$input_permissions = $dsb->input['fields_'.$usergroup['gid']];
				if(!is_array($input_permissions))
				{
					// Convering the comma separated list from Javascript form into a variable
					$input_permissions = explode(',' , $input_permissions);
				}
				foreach($input_permissions as $input_permission)
				{
					$dsb->input['permissions'][$usergroup['gid']][$input_permission] = 1;
				}
			}
		}
	}
	$sortable = "<script type=\"text/javascript\">\n$(function() {\n";
	foreach($usergroups as $usergroup)
	{
		$perms = array();
		if($dsb->input['default_permissions'][$usergroup['gid']])
		{
			if(is_array($existing_permissions) && $existing_permissions[$usergroup['gid']])
			{
				$perms = $existing_permissions[$usergroup['gid']];
				$default_checked = false;
			}
			elseif(is_array($cached_forum_perms) && $cached_forum_perms[$forum_data['fid']][$usergroup['gid']])
			{
				$perms = $cached_forum_perms[$forum_data['fid']][$usergroup['gid']];
				$default_checked = true;
			}
			else if(is_array($cached_forum_perms) && $cached_forum_perms[$forum_data['pid']][$usergroup['gid']])
			{
				$perms = $cached_forum_perms[$forum_data['pid']][$usergroup['gid']];
				$default_checked = true;
			}
		}
		
		if(!$perms)
		{
			$perms = $usergroup;
			$default_checked = true;
		}
		
		foreach($field_list as $forum_permission => $forum_perm_title)
		{
			if(isset($dsb->input['permissions']))
			{
				if($dsb->input['default_permissions'][$usergroup['gid']])
				{
					$default_checked = true;
				}
				else
				{
					$default_checked = false;
				}
				
				if($dsb->input['permissions'][$usergroup['gid']][$forum_permission])
				{
					$perms_checked[$forum_permission] = 1;
				}
				else
				{
					$perms_checked[$forum_permission] = 0;
				}
			}
			else
			{
				if($perms[$forum_permission] == 1)
				{
					$perms_checked[$forum_permission] = 1;
				}
				else
				{
					$perms_checked[$forum_permission] = 0;
				}
			}
		}
		$usergroup['title'] = htmlspecialchars_uni($usergroup['title']);
		
		if($default_checked)
		{
			$inherited_text = $locale['inherited_permission'];
		}
		else
		{
			$inherited_text = $locale['custom_permission'];
		}
		
		$form_container->output_cell("<strong>{$usergroup['title']}</strong><br />".$form->generate_check_box("default_permissions[{$usergroup['gid']}]", 1, "", array("id" => "default_permissions_{$usergroup['gid']}", "checked" => $default_checked, "onclick" => $default_click))." <small><label for=\"default_permissions_{$usergroup['gid']}\">{$locale['permissions_use_group_default']}</label></small>");
		
        
        $sortable .= "      $(\"#fields_enabled_{$usergroup['gid']}, #fields_disabled_{$usergroup['gid']}\").sortable({\n";
        $sortable .= "          connectWith: '.field_perms_{$usergroup['gid']}',placeholder: 'sort-placeholder'\n";
        $sortable .= "      }).disableSelection();\n";

		$field_select = "<div class=\"quick_perm_fields\">\n";
        
		$field_select .= "<div class=\"enabled\"><div class=\"fields_title\">{$locale['enabled']}</div><ul id=\"fields_enabled_{$usergroup['gid']}\" class=\"field_perms_{$usergroup['gid']}\">\n";
		
        foreach($perms_checked as $perm => $value)
		{
			if($value == 1)
			{
				$field_select .= "<li id=\"field-{$perm}\" class=\"tbl tbl-border\">{$field_list2[$perm]}</li>";
			}
		}
		$field_select .= "</ul></div>\n";
		$field_select .= "<div class=\"disabled\"><div class=\"fields_title\">{$locale['disabled']}</div><ul id=\"fields_disabled_{$usergroup['gid']}\" class=\"field_perms_{$usergroup['gid']}\">\n";
		foreach($perms_checked as $perm => $value)
		{
			if($value == 0)
			{
				$field_select .= "<li id=\"field-{$perm}\" class=\"tbl tbl-border\">{$field_list2[$perm]}</li>";
			}
		}
		$field_select .= "</ul></div>";
        echo "</div>\n";
        
		$field_select .= $form->generate_hidden_field("fields_".$usergroup['gid'], @implode(",", @array_keys($perms_checked, '1')), array('id' => 'fields_'.$usergroup['gid']));
		$field_select = str_replace("'", "\\'", $field_select);
		$field_select = str_replace("\n", "", $field_select);
		

		
		$field_selected = array();
		foreach($field_list as $forum_permission => $permission_title)
		{
			$field_options[$forum_permission] = $permission_title;
			if($perms_checked[$forum_permission])
			{
				$field_selected[] = $forum_permission;
			}
		}
		
		$field_select .= "<noscript>".$form->generate_select_box('fields_'.$usergroup['gid'].'[]', $field_options, $field_selected, array('id' => 'fields_'.$usergroup['gid'].'[]', 'multiple' => true))."</noscript>\n";
		$form_container->output_cell($field_select, array('colspan' => 2));
		
		$form_container->construct_row();
		
		$ids[] = $usergroup['gid'];
	}
    $sortable .= "});\n</script>";
    add_to_head($sortable);
	$form_container->end();

	$buttons[] = $form->generate_submit_button($locale['save_forum'],array('class' => 'button'));
	$form->output_submit_wrapper($buttons);
    
	$form->end();
	
	/*Write in our JS based field selector
	echo "<script type=\"text/javascript\">\n<!--\n";
	foreach($ids as $id)
	{
		echo "Event.observe(window, 'load', function(){ QuickPermEditor.init(".$id.") });\n";
	}
	echo "// -->\n</script>\n";*/
	

}

if($dsb->input['action'] == "edit")
{
	
	if(!$dsb->input['fid'])
	{
		flash_message($locale['error_invalid_fid'], 'error');
		admin_redirect("index.php?module=forum-management");
	}
	
	$query = dbquery("SELECT f.*,f2.* FROM ".DB_FORUMS." f 
                        LEFT JOIN  ".DB_DSB_FORUMS." f2 ON f2.fid=f.forum_id
                        WHERE fid='{$dsb->input['fid']}'");
	$forum_data = dbarray($query);
	if(!$forum_data)
	{
		flash_message($locale['error_invalid_fid'], 'error');
		admin_redirect("index.php?module=forum-management");
	}
	
	$fid = intval($dsb->input['fid']);
	
	if($dsb->request_method == "post")
	{
		if(!trim($dsb->input['title']))
		{
			$errors[] = $locale['error_missing_title'];
		}
		
		$pid = intval($dsb->input['pid']);
		
		if($pid == $dsb->input['fid'])
		{
			$errors[] = $locale['error_forum_parent_itself'];
		}
		else
		{
			$query = dbquery("SELECT * FROM ".DB_DSB_FORUMS." WHERE pid='{$dsb->input['fid']}'");
			while($child = dbarray($query))
			{
				if($child['fid'] == $pid)
				{
					$errors[] = $locale['error_forum_parent_child'];
					break;
				}
			}
		}
		
		$type = $dsb->input['type'];
		
		if($pid <= 0 && $type == "f")
		{
			$errors[] = $locale['error_no_parent'];
		}		
		
		if($type == 'c' && $forum_data['type'] == 'f')
		{
			$query = $db->simple_select('threads', 'COUNT(tid) as num_threads', "fid = '{$fid}'");
			if($db->fetch_field($query, "num_threads") > 0)
			{
				$errors[] = $locale['error_not_empty'];
			}
		}
		
		if(!$errors)
		{
			if($pid < 0)
			{
				$pid = 0;
			}
            $update_array = array(
                "forum_name" => dsb_escape_string($dsb->input['title']),
                "forum_order" => intval($dsb->input['disporder']),
                "forum_description" => dsb_escape_string($dsb->input['description']),
                "forum_access" => "101",
            );
            dbupdate(DB_FORUMS, $update_array, "forum_id='{$fid}'");
			$update_array2 = array(
				"linkto" => dsb_escape_string($dsb->input['linkto']),
				"type" => dsb_escape_string($type),
				"pid" => $pid,
				"active" => intval($dsb->input['active']),
				"open" => intval($dsb->input['open']),
				"allowhtml" => intval($dsb->input['allowhtml']),
				"allowmycode" => intval($dsb->input['allowmycode']),
				"allowsmilies" => intval($dsb->input['allowsmilies']),
				"allowimgcode" => intval($dsb->input['allowimgcode']),
				"allowvideocode" => intval($dsb->input['allowvideocode']),
				"allowpicons" => intval($dsb->input['allowpicons']),
				"allowtratings" => intval($dsb->input['allowtratings']),
				"usepostcounts" => intval($dsb->input['usepostcounts']),
				"showinjump" => intval($dsb->input['showinjump']),
				"modposts" => intval($dsb->input['modposts']),
				"modthreads" => intval($dsb->input['modthreads']),
				"mod_edit_posts" => intval($dsb->input['mod_edit_posts']),
				"modattachments" => intval($dsb->input['modattachments']),
				"defaultdatecut" => intval($dsb->input['defaultdatecut']),
				"defaultsortby" => dsb_escape_string($dsb->input['defaultsortby']),
				"defaultsortorder" => dsb_escape_string($dsb->input['defaultsortorder']),
			);
			dbupdate(DB_DSB_FORUMS, $update_array2, "fid='{$fid}'");
			if($pid != $forum_data['pid'])
			{
				// Update the parentlist of this forum.
				$db->update_query("forums", array("parentlist" => make_parent_list($fid)), "fid='{$fid}'", 1);
				
				// Rebuild the parentlist of all of the subforums of this forum
				switch($db->type)
				{
					case "sqlite":
					case "pgsql":
						$query = $db->simple_select("forums", "fid", "','||parentlist||',' LIKE '%,$fid,%'");
						break;
					default:
						$query = $db->simple_select("forums", "fid", "CONCAT(',',parentlist,',') LIKE '%,$fid,%'");
				}
				
				while($child = $db->fetch_array($query))
				{
					$db->update_query("forums", array("parentlist" => make_parent_list($child['fid'])), "fid='{$child['fid']}'", 1);
				}
			}
			
			$inherit = $dsb->input['default_permissions'];
			
            
			foreach($dsb->input as $id => $permission)
			{
				// Make sure we're only skipping inputs that don't start with "fields_" and aren't fields_default_ or fields_inherit_
				if($id === false || (strpos($id, 'fields_default_') !== false || strpos($id, 'fields_inherit_') !== false))
				{
					continue;
				}
				
				list(, $gid) = explode('fields_', $id);
				
				if($dsb->input['fields_default_'.$gid] == $permission && $dsb->input['fields_inherit_'.$gid] == 1)
				{
					$inherit[$gid] = 1;
					continue;
				}
				$inherit[$gid] = 0;
				echo $permission;
				// If it isn't an array then it came from the javascript form
				if(!is_array($permission))
				{
					$permission = explode(',', $permission);
					$permission = array_flip($permission);
					foreach($permission as $name => $value)
					{
						$permission[$name] = 1;
					}
				}
				
				foreach(array('canview','canpostthreads','canpostreplys','canpostpolls') as $name)
				{
					if(in_array($name, $permission) || $permission[$name])
					{
						$permissions[$name][$gid] = 1;
					}
					else
					{
						$permissions[$name][$gid] = 0;
					}
				}
			}
			

            
			$cache->update_forums();
			
			$canview = $permissions['canview'];
			$canpostthreads = $permissions['canpostthreads'];
			$canpostpolls = $permissions['canpostpolls'];
			$canpostattachments = $permissions['canpostattachments'];
			$canpostreplies = $permissions['canpostreplys'];
			
            
            
            
			save_quick_perms($fid);
			

			
			// Log admin action
			//log_admin_action($fid, $dsb->input['title']);
			
			//flash_message($locale['success_forum_updated'], 'success');
			redirect("index.php{$aidlink}&amp;module=forums");
		}
	}
	
	//$page->extra_header .= "<script src=\"../jscripts/scriptaculous.js?load=effects,dragdrop,controls\" type=\"text/javascript\"></script>\n";
	add_to_head("<script src=\"".DSB_DIR."js/perm_edit.js\" type=\"text/javascript\"></script>\n");
	//$page->extra_header .=  "<script src=\"jscripts/imodal.js\" type=\"text/javascript\"></script>\n";
	//$page->extra_header .=  "<link rel=\"stylesheet\" type=\"text/css\" href=\"styles/default/imodal.css\" />\n";
	
	//$page->add_breadcrumb_item($locale['edit_forum']);
	//$page->output_header($locale['edit_forum']);
		
	//$page->output_nav_tabs($sub_tabs, 'edit_forum_settings');
	
	$form = new Form("index.php{$aidlink}&amp;module=forums&amp;action=edit", "post");
	echo $form->generate_hidden_field("fid", $fid);

	if($errors)
	{
		echo output_inline_error($errors);
		$forum_data = $dsb->input;
	}
	else
	{
		$forum_data['title'] = $forum_data['forum_name'];
	}
	
	$query = dbquery("SELECT * FROM ".DB_DSB_USERGROUPS);
	while($usergroup = dbarray($query))
	{
		$usergroups[$usergroup['gid']] = $usergroup;
	}
	
	$query = dbquery("SELECT * FROM ".DB_DSB_FORUMPERMS." WHERE fid='{$fid}'");
	while($existing = dbarray($query))
	{
		$existing_permissions[$existing['gid']] = $existing;
	}
	
	$types = array(
		'f' => $locale['forum'],
		'c' => $locale['category']
	);
	
	$create_a_options_f = array(
		'id' => 'forum'
	);
	
	$create_a_options_c = array(
		'id' => 'category'
	);
	
	if($forum_data['type'] == "f")
	{
		$create_a_options_f['checked'] = true;
	}
	else
	{
		$create_a_options_c['checked'] = true;
	}
    echo "<br />";
	$form_container = new FormContainer($locale['edit_forum'],"form_container");
	$form_container->output_row($locale['create_a'], $locale['create_a_desc'], $form->generate_radio_button('type', 'f', $locale['forum'], $create_a_options_f)."<br />\n".$form->generate_radio_button('type', 'c', $locale['category'], $create_a_options_c));
	$form_container->output_row($locale['title']." <em>*</em>", "", $form->generate_text_box('title', $forum_data['title'], array('id' => 'title')), 'title');
	$form_container->output_row($locale['description'], "", $form->generate_text_area('description', $forum_data['forum_description'], array('id' => 'description')), 'description');
	$form_container->output_row($locale['parent_forum']." <em>*</em>", $locale['parent_forum_desc'], $form->generate_forum_select('pid', $forum_data['pid'], array('id' => 'pid', 'main_option' => $locale['none'])), 'pid');
	$form_container->output_row($locale['display_order'], "", $form->generate_text_box('disporder', $forum_data['forum_order'], array('id' => 'disporder')), 'disporder');
	$form_container->end();
	
	$form_container = new FormContainer($locale['additional_forum_options'],"form_container");
	$form_container->output_row($locale['forum_link'], $locale['forum_link_desc'], $form->generate_text_box('linkto', $forum_data['linkto'], array('id' => 'linkto')), 'linkto');
	
	$access_options = array(
		$form->generate_check_box('active', 1, $locale['forum_is_active']."<br />\n<small>{$locale['forum_is_active_desc']}</small>", array('checked' => $forum_data['active'], 'id' => 'active')),
		$form->generate_check_box('open', 1, $locale['forum_is_open']."<br />\n<small>{$locale['forum_is_open_desc']}</small>", array('checked' => $forum_data['open'], 'id' => 'open'))
	);
		
	$form_container->output_row($locale['access_options'], "", "<div class=\"forum_settings_bit\">".implode("</div><div class=\"forum_settings_bit\">", $access_options)."</div>");
	
	$moderator_options = array(
		$form->generate_check_box('modposts', 1, $locale['mod_new_posts'], array('checked' => $forum_data['modposts'], 'id' => 'modposts')),
		$form->generate_check_box('modthreads', 1, $locale['mod_new_threads'], array('checked' => $forum_data['modthreads'], 'id' => 'modthreads')),
		$form->generate_check_box('modattachments', 1, $locale['mod_new_attachments'], array('checked' => $forum_data['modattachments'], 'id' => 'modattachments')),
		$form->generate_check_box('mod_edit_posts',1, $locale['mod_after_edit'], array('checked' => $forum_data['mod_edit_posts'], 'id' => 'mod_edit_posts'))
	);
	
	$form_container->output_row($locale['moderation_options'], "", "<div class=\"forum_settings_bit\">".implode("</div><div class=\"forum_settings_bit\">", $moderator_options)."</div>");
	
	
	$default_date_cut = array(
		0 => $locale['board_default'],
		1 => $locale['datelimit_1day'],
		5 => $locale['datelimit_5days'],
		10 => $locale['datelimit_10days'],
		20 => $locale['datelimit_20days'],
		50 => $locale['datelimit_50days'],
		75 => $locale['datelimit_75days'],
		100 => $locale['datelimit_100days'],
		365 => $locale['datelimit_lastyear'],
		9999 => $locale['datelimit_beginning'],
	);
	
	$default_sort_by = array(
		"" => $locale['board_default'],
		"subject" => $locale['sort_by_subject'],
		"lastpost" => $locale['sort_by_lastpost'],
		"starter" => $locale['sort_by_starter'],
		"started" => $locale['sort_by_started'],
		"rating" => $locale['sort_by_rating'],
		"replies" => $locale['sort_by_replies'],
		"views" => $locale['sort_by_views'],
	);
	
	$default_sort_order = array(
		"" => $locale['board_default'],
		"asc" => $locale['sort_order_asc'],
		"desc" => $locale['sort_order_desc'],
	);
	
	$view_options = array(
		$locale['default_date_cut']."<br />\n".$form->generate_select_box('defaultdatecut', $default_date_cut, $forum_data['defaultdatecut'], array('checked' => $forum_data['defaultdatecut'], 'id' => 'defaultdatecut')),
		$locale['default_sort_by']."<br />\n".$form->generate_select_box('defaultsortby', $default_sort_by, $forum_data['defaultsortby'], array('checked' => $forum_data['defaultsortby'], 'id' => 'defaultsortby')),
		$locale['default_sort_order']."<br />\n".$form->generate_select_box('defaultsortorder', $default_sort_order, $forum_data['defaultsortorder'], array('checked' => $forum_data['defaultsortorder'], 'id' => 'defaultsortorder')),
	);
	
	$form_container->output_row($locale['default_view_options'], "", "<div class=\"forum_settings_bit\">".implode("</div><div class=\"forum_settings_bit\">", $view_options)."</div>");
	
	$misc_options = array(
		$form->generate_check_box('allowhtml', 1, $locale['allow_html'], array('checked' => $forum_data['allowhtml'], 'id' => 'allowhtml')),
		$form->generate_check_box('allowmycode', 1, $locale['allow_mycode'], array('checked' => $forum_data['allowmycode'], 'id' => 'allowmycode')),
		$form->generate_check_box('allowsmilies', 1, $locale['allow_smilies'], array('checked' => $forum_data['allowsmilies'], 'id' => 'allowsmilies')),
		$form->generate_check_box('allowimgcode', 1, $locale['allow_img_code'], array('checked' => $forum_data['allowimgcode'], 'id' => 'allowimgcode')),
		$form->generate_check_box('allowvideocode', 1, $locale['allow_video_code'], array('checked' => $forum_data['allowvideocode'], 'id' => 'allowvideocode')),
		$form->generate_check_box('allowpicons', 1, $locale['allow_post_icons'], array('checked' => $forum_data['allowpicons'], 'id' => 'allowpicons')),
		$form->generate_check_box('allowtratings', 1, $locale['allow_thread_ratings'], array('checked' => $forum_data['allowtratings'], 'id' => 'allowtratings')),
		$form->generate_check_box('showinjump', 1, $locale['show_forum_jump'], array('checked' => $forum_data['showinjump'], 'id' => 'showinjump')),
		$form->generate_check_box('usepostcounts', 1, $locale['use_postcounts'], array('checked' => $forum_data['usepostcounts'], 'id' => 'usepostcounts'))
	);
	
	$form_container->output_row($locale['misc_options'], "", "<div class=\"forum_settings_bit\">".implode("</div><div class=\"forum_settings_bit\">", $misc_options)."</div>");
	$form_container->end();
	
	$cached_forum_perms = $cache->read("forumpermissions");
	$field_list = array(
		'canview' => $locale['permissions_canview'],
		'canpostthreads' => $locale['permissions_canpostthreads'],
		'canpostreplys' => $locale['permissions_canpostreplys'],
		'canpostpolls' => $locale['permissions_canpostpolls'],
	);
	
	$field_list2 = array(
		'canview' => $locale['perm_drag_canview'],
		'canpostthreads' => $locale['perm_drag_canpostthreads'],
		'canpostreplys' => $locale['perm_drag_canpostreplys'],
		'canpostpolls' => $locale['perm_drag_canpostpolls'],
	);
	
	$ids = array();
	
	$form_container = new FormContainer(ds_sprintf($locale['forum_permissions_in'], $forum_data['title']),"form_container");
	$form_container->output_row_header($locale['usergroup'], array("class" => "align_center", 'style' => 'width: 30%'));
	$form_container->output_row_header($locale['permissions'], array("class" => "align_center"));
	$form_container->output_row_header($locale['controls'], array("class" => "align_center", 'colspan' => '2', 'width' => '120px'));
	
	if($dsb->request_method == "post")
	{
		foreach($usergroups as $usergroup)
		{
			if(isset($dsb->input['fields_'.$usergroup['gid']]))
			{
				$input_permissions = $dsb->input['fields_'.$usergroup['gid']];
				if(!is_array($input_permissions))
				{
					// Convering the comma separated list from Javascript form into a variable
					$input_permissions = explode(',' , $input_permissions);
				}
				foreach($input_permissions as $input_permission)
				{
					$dsb->input['permissions'][$usergroup['gid']][$input_permission] = 1;
				}
			}
		}
	}
	foreach($usergroups as $usergroup)
	{
		$perms = array();
		if(isset($dsb->input['default_permissions']))
		{
			if($dsb->input['default_permissions'][$usergroup['gid']])
			{
				if(is_array($existing_permissions) && $existing_permissions[$usergroup['gid']])
				{
					$perms = $existing_permissions[$usergroup['gid']];
					$default_checked = false;
				}
				elseif(is_array($cached_forum_perms) && $cached_forum_perms[$forum_data['fid']][$usergroup['gid']])
				{
					$perms = $cached_forum_perms[$forum_data['fid']][$usergroup['gid']];
					$default_checked = true;
				}
				else if(is_array($cached_forum_perms) && $cached_forum_perms[$forum_data['pid']][$usergroup['gid']])
				{
					$perms = $cached_forum_perms[$forum_data['pid']][$usergroup['gid']];
					$default_checked = true;
				}
			}
			
			if(!$perms)
			{
				$perms = $usergroup;
				$default_checked = true;
			}
		}
		else
		{
			if(is_array($existing_permissions) && $existing_permissions[$usergroup['gid']])
			{
				$perms = $existing_permissions[$usergroup['gid']];
				$default_checked = false;
			}
			elseif(is_array($cached_forum_perms) && $cached_forum_perms[$forum_data['fid']][$usergroup['gid']])
			{
				$perms = $cached_forum_perms[$forum_data['fid']][$usergroup['gid']];
				$default_checked = true;
			}
			else if(is_array($cached_forum_perms) && $cached_forum_perms[$forum_data['pid']][$usergroup['gid']])
			{
				$perms = $cached_forum_perms[$forum_data['pid']][$usergroup['gid']];
				$default_checked = true;
			}
			
			if(!$perms)
			{
				$perms = $usergroup;
				$default_checked = true;
			}
		}
		
		foreach($field_list as $forum_permission => $forum_perm_title)
		{
			if(isset($dsb->input['permissions']))
			{
				if($dsb->input['permissions'][$usergroup['gid']][$forum_permission])
				{
					$perms_checked[$forum_permission] = 1;
				}
				else
				{
					$perms_checked[$forum_permission] = 0;
				}
			}
			else
			{
				if($perms[$forum_permission] == 1)
				{
					$perms_checked[$forum_permission] = 1;
				}
				else
				{
					$perms_checked[$forum_permission] = 0;
				}
			}
		}

		$usergroup['title'] = htmlspecialchars_uni($usergroup['title']);
		
		if($default_checked)
		{
			$inherited_text = $locale['inherited_permission'];
		}
		else
		{
			$inherited_text = $locale['custom_permission'];
		}
		
		$form_container->output_cell("<strong>{$usergroup['title']}</strong> <small>({$inherited_text})</small>",'','','',array('colspan' => '5','style' => 'padding: 3px;'));


		$field_select = "<div class=\"quick_perm_fields\"></div>\n";
		$field_select .= $form->generate_hidden_field("fields_".$usergroup['gid'], @implode(",", @array_keys($perms_checked, '1')), array('id' => 'fields_'.$usergroup['gid']));
		$field_select .= $form->generate_hidden_field("fields_inherit_".$usergroup['gid'], (int)$default_checked, array('id' => 'fields_inherit_'.$usergroup['gid']));
		$field_select .= $form->generate_hidden_field("fields_default_".$usergroup['gid'], @implode(",", @array_keys($perms_checked, '1')), array('id' => 'fields_default_'.$usergroup['gid']));
		$field_select = str_replace("'", "\\'", $field_select);
		$field_select = str_replace("\n", "", $field_select);
		

		
		$field_selected = array();
		foreach($field_list as $forum_permission => $permission_title)
		{
			$field_options[$forum_permission] = $permission_title;
			if($perms_checked[$forum_permission])
			{
				$field_selected[] = $forum_permission;
			}
		}
		
		$field_select .= "".$form->generate_select_box('fields_'.$usergroup['gid'].'[]', $field_options, $field_selected, array('id' => 'fields_'.$usergroup['gid'].'[]', 'multiple' => true))."\n";
		
        $form_container->output_cell($field_select,array('style' => 'font-size: 10px;text-align: center;'));
        
		if(!$default_checked)
		{
			$form_container->output_cell("<a href=\"index.php?module=forum-management&amp;action=permissions&amp;pid={$perms['pid']}\" onclick=\"modal = new MyModal({type: 'ajax', url: 'index.php?module=forum-management&action=permissions&pid={$perms['pid']}&ajax=1'}); return false;\">{$locale['edit_permissions']}</a>", array("class" => "align_center"));
			$form_container->output_cell("<a href=\"index.php?module=forum-management&amp;action=clear_permission&amp;pid={$perms['pid']}&amp;my_post_key={$dsb->post_code}\" onclick=\"return AdminCP.deleteConfirmation(this, '{$locale['confirm_clear_custom_permission']}')\">{$locale['clear_custom_perms']}</a>", array("class" => "align_center"));
		}
		else
		{
			$form_container->output_cell("<a href=\"index.php?module=forum-management&amp;action=permissions&amp;gid={$usergroup['gid']}&amp;fid={$fid}\" onclick=\"modal = new MyModal({type: 'ajax', url: 'index.php?module=forum-management&action=permissions&gid={$usergroup['gid']}&fid={$fid}&ajax=1'}); return false;\">{$locale['set_custom_perms']}</a>", array("class" => "align_center", "colspan" => 2));
		}
		$form_container->construct_row(array('id' => 'row_'.$usergroup['gid']));
		
		$ids[] = $usergroup['gid'];
	}

    

	$form_container->end();
	
	$buttons[] = $form->generate_submit_button($locale['save_forum'],array('class' => 'button'));
	$form->output_submit_wrapper($buttons);
	$form->end();

	// Write in our JS based field selector
    /*
	$quick_perms = "<script type=\"text/javascript\">\n<!--\n(function($) {\n";
	foreach($ids as $id)
	{
		$quick_perms .= "$(document).ready(function($){ QuickPermEditor.init(".$id."); });\n";
	}
	$quick_perms .= "})(jQuery);\n// -->\n</script>\n";
	add_to_head($quick_perms);*/
}




if(!$dsb->input['action'])
{
	$fid = intval($dsb->input['fid']);
	if($dsb->request_method == "post")
	{
		if($fid)
		{
			$forum = get_forum($fid);
		}
		if($dsb->input['update'] == "permissions")
		{
			$inherit = array();
			foreach($dsb->input as $id => $permission)
			{
				// Make sure we're only skipping inputs that don't start with "fields_" and aren't fields_default_ or fields_inherit_
				if(strpos($id, 'fields_') === false || (strpos($id, 'fields_default_') !== false || strpos($id, 'fields_inherit_') !== false))
				{
					continue;
				}
				
				list(, $gid) = explode('fields_', $id);
				
				if($dsb->input['fields_default_'.$gid] == $permission && $dsb->input['fields_inherit_'.$gid] == 1)
				{
					$inherit[$gid] = 1;
					continue;
				}
				$inherit[$gid] = 0;
				
				// If it isn't an array then it came from the javascript form
				if(!is_array($permission))
				{
					$permission = explode(',', $permission);
					$permission = array_flip($permission);
					foreach($permission as $name => $value)
					{
						$permission[$name] = 1;
					}
				}
				foreach(array('canview','canpostthreads','canpostreplys','canpostpolls') as $name)
				{
					if($permission[$name])
					{
						$permissions[$name][$gid] = 1;
					}
					else
					{
						$permissions[$name][$gid] = 0;
					}
				}
			}
			
			$cache->update_forums();
			
			$canview = $permissions['canview'];
			$canpostthreads = $permissions['canpostthreads'];
			$canpostpolls = $permissions['canpostpolls'];
			$canpostattachments = $permissions['canpostattachments'];
			$canpostreplies = $permissions['canpostreplys'];
			
			save_quick_perms($fid);
			
			$plugins->run_hooks("admin_forum_management_start_permissions_commit");
			
			// Log admin action
			log_admin_action('quickpermissions', $fid, $forum['name']);
			
			flash_message($locale['success_forum_permissions_updated'], 'success');
			admin_redirect("index.php?module=forum-management&fid={$fid}#tab_permissions");
		}
		elseif($dsb->input['add'] == "moderators")
		{
			
			$forum = get_forum($fid);
			if(!$forum)
			{
				flash_message($locale['error_invalid_forum'], 'error');
				admin_redirect("index.php?module=forum-management&fid={$fid}#tab_moderators");
			}
			if (!empty($dsb->input['usergroup']))
			{
				$query = $db->simple_select("usergroups", "gid AS id, title AS name", "title='".dsb_escape_string($dsb->input['usergroup'])."'", array('limit' => 1));
				$isgroup = 1;
			}
			else
			{
				$query = $db->simple_select("users", "uid AS id, username AS name", "username='".dsb_escape_string($dsb->input['username'])."'", array('limit' => 1));
				$isgroup = 0;
			}
			$newmod = $db->fetch_array($query);
			if($newmod['id'])
			{
				$query = $db->simple_select("moderators", "id", "id='".$newmod['id']."' AND fid='".$fid."' AND isgroup='{$isgroup}'", array('limit' => 1));
				$mod = $db->fetch_array($query);
				if(!$mod['id'])
				{
					$new_mod = array(
						"fid" => $fid,
						"id" => $newmod['id'],
						"isgroup" => $isgroup,
						"caneditposts" => 1,
						"candeleteposts" => 1,
						"canviewips" => 1,
						"canopenclosethreads" => 1,
						"canmanagethreads" => 1,
						"canmovetononmodforum" => 1
					);
					$mid = $db->insert_query("moderators", $new_mod);
					
					if(!$isgroup)
					{
						$db->update_query("users", array('usergroup' => 6), "uid='{$newmod['id']}' AND usergroup='2'");
					}
					$cache->update_moderators();
					
					$plugins->run_hooks("admin_forum_management_start_moderators_commit");
					
					// Log admin action
					log_admin_action('addmod', $new_mod['fid'], $newmod['name'], $fid, $forum['name']);
					
					flash_message($locale['success_moderator_added'], 'success');
					admin_redirect("index.php?module=forum-management&action=editmod&mid={$mid}");
				}
				else
				{
					flash_message($locale['error_moderator_already_added'], 'error');
					admin_redirect("index.php?module=forum-management&fid={$fid}#tab_moderators");
				}
			}
			else
			{
				flash_message($locale['error_moderator_not_found'], 'error');
				admin_redirect("index.php?module=forum-management&fid={$fid}#tab_moderators");
			}
		}
		else
		{
			if(!empty($dsb->input['disporder']) && is_array($dsb->input['disporder']))
			{
				foreach($dsb->input['disporder'] as $update_fid => $order)
				{
					dbquery("UPDATE ".DB_FORUMS." SET forum_order=".intval($order)." WHERE forum_id='".intval($update_fid)."'");
				}
						
				$cache->update_forums();
				

				
				// Log admin action
				//log_admin_action('orders', $forum['fid'], $forum['name']);
			
				//flash_message($locale['success_forum_disporder_updated'], 'success');
				redirect("index.php{$aidlink}&amp;module=forums");
			}
		}
	}
	
    /*
	$page->extra_header .= "<script src=\"../jscripts/scriptaculous.js?load=effects,dragdrop,controls\" type=\"text/javascript\"></script>\n";
	$page->extra_header .=  "<script src=\"jscripts/quick_perm_editor.js\" type=\"text/javascript\"></script>\n";
	$page->extra_header .=  "<script src=\"jscripts/imodal.js\" type=\"text/javascript\"></script>\n";
	$page->extra_header .=  "<link rel=\"stylesheet\" type=\"text/css\" href=\"styles/default/imodal.css\" />\n";
	*/
    
	if($fid)
	{
		//$page->add_breadcrumb_item($locale['view_forum'], "index.php?module=forum-management");
	}
	
	
	/*
	if($fid)
	{
		$page->output_nav_tabs($sub_tabs, 'view_forum');
	}
	else
	{
		$page->output_nav_tabs($sub_tabs, 'forum_management');
	}
    */
	echo "<br />";
	$form = new Form("index.php{$aidlink}&amp;module=forums", "post", "management");
	echo $form->generate_hidden_field("fid", $dsb->input['fid']);
	
    $tabid = "manage";
	if($fid)
	{
        add_to_head("<script type=\"text/javascript\" src=\"".DSB_DIR."js/jquery.idTabs.js\"></script>");
		$tabs = array(
			'subforums' => $locale['subforums'],
			'permissions' => $locale['forum_permissions'],
			'moderators' => $locale['moderators'],
		);
		
		output_tab_control($tabs,$tabid);
	
		echo "<div id=\"{$tabid}-tab1\" style=\"display: block;\">\n";
		if(!is_array($forum_cache))
		{
			cache_forums();
		}
		$form_container = new FormContainer(ds_sprintf($locale['in_forums'], $forum_cache[$fid]['forum_name']),"form_container");
	}
	else
	{
		$form_container = new FormContainer($locale['manage_forums'],"form_container");
	}
	$form_container->output_row_header($locale['forum']);
	$form_container->output_row_header($locale['order'], array("class" => "align_center", 'width' => '5%'));
	$form_container->output_row_header($locale['controls'], array("class" => "align_center", 'style' => 'width: 200px'));
	
	build_admincp_forums_list($form_container, $fid);
	
	$submit_options = array('class' => 'button');
	
	if($form_container->num_rows() == 0)
	{
		$form_container->output_cell($locale['no_forums'], array('colspan' => 3));
		$form_container->construct_row();
		$submit_options = array('disabled' => true);
	}
	
	$form_container->end();
	
	$buttons[] = $form->generate_submit_button($locale['save_submit'], $submit_options);
	$buttons[] = $form->generate_reset_button($locale['reset_submit'], array('class' => 'button'));	
	
	$form->output_submit_wrapper($buttons);
	
	if(!$fid)
	{
		$form->end();
	}
	
	if($fid)
	{
		echo "</div>\n";
		$form->end();
		
		$query = dbquery("SELECT * FROM ".DB_DSB_USERGROUPS." ORDER BY title");
		while($usergroup = dbarray($query))
		{
			$usergroups[$usergroup['gid']] = $usergroup;
		}
		
		$query = dbquery("SELECT * FROM ".DB_DSB_FORUMPERMS." WHERE fid='{$fid}'");
		while($existing = dbarray($query))
		{
			$existing_permissions[$existing['gid']] = $existing;
		}
	
		$cached_forum_perms = $cache->read("forumpermissions");
		$field_list = array(
			'canview' => $locale['permissions_canview'],
			'canpostthreads' => $locale['permissions_canpostthreads'],
			'canpostreplys' => $locale['permissions_canpostreplys'],
			'canpostpolls' => $locale['permissions_canpostpolls'],
		);
		
		$field_list2 = array(
			'canview' => $locale['perm_drag_canview'],
			'canpostthreads' => $locale['perm_drag_canpostthreads'],
			'canpostreplys' => $locale['perm_drag_canpostreplys'],
			'canpostpolls' => $locale['perm_drag_canpostpolls'],
		);
		
		$ids = array();
		
		$form = new Form("index.php?module=forums", "post", "management");
		echo $form->generate_hidden_field("fid", $dsb->input['fid']);
		echo $form->generate_hidden_field("update", "permissions");
				
		echo "<div id=\"{$tabid}-tab2\" style=\"display: none;\">\n";
		
		$form_container = new FormContainer(ds_sprintf($locale['forum_permissions_in'], $forum_cache[$fid]['forum_name']),"form_container");
		$form_container->output_row_header($locale['permissions_group'], array("class" => "align_center", 'style' => 'width: 30%'));
		$form_container->output_row_header($locale['overview_allowed_actions'], array("class" => "align_center"));
		$form_container->output_row_header($locale['overview_disallowed_actions'], array("class" => "align_center"));
		$form_container->output_row_header($locale['controls'], array("class" => "align_center", 'style' => 'width: 120px', 'colspan' => 2));
		foreach($usergroups as $usergroup)
		{
			$perms = array();
			if(isset($dsb->input['default_permissions']))
			{
				if($dsb->input['default_permissions'][$usergroup['gid']])
				{
					if(is_array($existing_permissions) && $existing_permissions[$usergroup['gid']])
					{
						$perms = $existing_permissions[$usergroup['gid']];
						$default_checked = false;
					}
					elseif(is_array($cached_forum_perms) && $cached_forum_perms[$forum_data['fid']][$usergroup['gid']])
					{
						$perms = $cached_forum_perms[$forum_data['fid']][$usergroup['gid']];
						$default_checked = true;
					}
					else if(is_array($cached_forum_perms) && $cached_forum_perms[$forum_data['pid']][$usergroup['gid']])
					{
						$perms = $cached_forum_perms[$forum_data['pid']][$usergroup['gid']];
						$default_checked = true;
					}
				}
				
				if(!$perms)
				{
					$perms = $usergroup;
					$default_checked = true;
				}
			}
			else
			{
				if(is_array($existing_permissions) && $existing_permissions[$usergroup['gid']])
				{
					$perms = $existing_permissions[$usergroup['gid']];
					$default_checked = false;
				}
				elseif(is_array($cached_forum_perms) && $cached_forum_perms[$forum_data['fid']][$usergroup['gid']])
				{
					$perms = $cached_forum_perms[$forum_data['fid']][$usergroup['gid']];
					$default_checked = true;
				}
				else if(is_array($cached_forum_perms) && $cached_forum_perms[$forum_data['pid']][$usergroup['gid']])
				{
					$perms = $cached_forum_perms[$forum_data['pid']][$usergroup['gid']];
					$default_checked = true;
				}
				
				if(!$perms)
				{
					$perms = $usergroup;
					$default_checked = true;
				}
			}
			foreach($field_list as $forum_permission => $forum_perm_title)
			{				
				if(isset($dsb->input['permissions']))
				{
					if($dsb->input['permissions'][$usergroup['gid']][$forum_permission])
					{
						$perms_checked[$forum_permission] = 1;
					}
					else
					{
						$perms_checked[$forum_permission] = 0;
					}
				}
				else
				{
					if($perms[$forum_permission] == 1)
					{
						$perms_checked[$forum_permission] = 1;
					}
					else
					{
						$perms_checked[$forum_permission] = 0;
					}
				}
			}
			$usergroup['title'] = htmlspecialchars_uni($usergroup['title']);
			
			if($default_checked == 1)
			{
				$inherited_text = $locale['inherited_permission'];
			}
			else
			{
				$inherited_text = $locale['custom_permission'];
			}
			
			$form_container->output_cell("<strong>{$usergroup['title']}</strong> <small style=\"vertical-align: middle;\">({$inherited_text})</small>");
			
			$field_select = "<div class=\"quick_perm_fields\">\n";
			$field_select .= "<div class=\"enabled\"><div class=\"fields_title\">{$locale['enabled']}</div><ul id=\"fields_enabled_{$usergroup['gid']}\">\n";
			foreach($perms_checked as $perm => $value)
			{
				if($value == 1)
				{
					$field_select .= "<li id=\"field-{$perm}\">{$field_list2[$perm]}</li>";
				}
			}
			$field_select .= "</ul></div>\n";
			$field_select .= "<div class=\"disabled\"><div class=\"fields_title\">{$locale['disabled']}</div><ul id=\"fields_disabled_{$usergroup['gid']}\">\n";
			foreach($perms_checked as $perm => $value)
			{
				if($value == 0)
				{
					$field_select .= "<li id=\"field-{$perm}\">{$field_list2[$perm]}</li>";
				}
			}
			$field_select .= "</ul></div></div>\n";
			$field_select .= $form->generate_hidden_field("fields_".$usergroup['gid'], @implode(",", @array_keys($perms_checked, '1')), array('id' => 'fields_'.$usergroup['gid']));
			$field_select .= $form->generate_hidden_field("fields_inherit_".$usergroup['gid'], (int)$default_checked, array('id' => 'fields_inherit_'.$usergroup['gid']));
			$field_select .= $form->generate_hidden_field("fields_default_".$usergroup['gid'], @implode(",", @array_keys($perms_checked, '1')), array('id' => 'fields_default_'.$usergroup['gid']));
			$field_select = str_replace("'", "\\'", $field_select);
			$field_select = str_replace("\n", "", $field_select);
			
			$field_select = "<script type=\"text/javascript\">
//<![CDATA[
document.write('".str_replace("/", "\/", $field_select)."');
//]]>
</script>\n";
			
			$field_selected = array();
			foreach($field_list as $forum_permission => $permission_title)
			{
				$field_options[$forum_permission] = $permission_title;
				if($perms_checked[$forum_permission])
				{
					$field_selected[] = $forum_permission;
				}
			}
			
			$field_select .= "<noscript>".$form->generate_select_box('fields_'.$usergroup['gid'].'[]', $field_options, $field_selected, array('id' => 'fields_'.$usergroup['gid'].'[]', 'multiple' => true))."</noscript>\n";
			$form_container->output_cell($field_select, array('colspan' => 2));
			
			if(!$default_checked)
			{
				$form_container->output_cell("<a href=\"index.php?module=forum-management&amp;action=permissions&amp;pid={$perms['pid']}\" onclick=\"modal = new MyModal({type: 'ajax', url: 'index.php?module=forum-management&action=permissions&pid={$perms['pid']}&ajax=1'}); return false;\">{$locale['edit_permissions']}</a>", array("class" => "align_center"));
				$form_container->output_cell("<a href=\"index.php?module=forum-management&amp;action=clear_permission&amp;pid={$perms['pid']}&amp;my_post_key={$dsb->post_code}\" onclick=\"return AdminCP.deleteConfirmation(this, '{$locale['confirm_clear_custom_permission']}')\">{$locale['clear_custom_perms']}</a>", array("class" => "align_center"));
			}
			else
			{
				$form_container->output_cell("<a href=\"index.php?module=forum-management&amp;action=permissions&amp;gid={$usergroup['gid']}&amp;fid={$fid}\"  onclick=\"modal = new MyModal({type: 'ajax', url: 'index.php?module=forum-management&action=permissions&gid={$usergroup['gid']}&fid={$fid}&ajax=1'}); return false;\">{$locale['set_custom_perms']}</a>", array("class" => "align_center", "colspan" => 2));
			}
			$form_container->construct_row(array('id' => 'row_'.$usergroup['gid']));
			
			$ids[] = $usergroup['gid'];
		}
		$form_container->end();
		
		$buttons = array();
		$buttons[] = $form->generate_submit_button($locale['update_forum_permissions'], array("class" => "button"));
		$buttons[] = $form->generate_reset_button($locale['reset_submit'], array("class" => "button"));	
	
		$form->output_submit_wrapper($buttons);
		
		// Write in our JS based field selector
		echo "<script type=\"text/javascript\">\n<!--\n";
		foreach($ids as $id)
		{
			echo "Event.observe(window, 'load', function(){ QuickPermEditor.init(".$id.") });\n";
		}
		echo "// -->\n</script>\n";
		
		echo "</div>\n";
		$form->end();
		echo "<div id=\"{$tabid}-tab3\" style=\"display: none;\">\n";
		$form_container = new FormContainer(ds_sprintf($locale['moderators_assigned_to'], $forum_cache[$fid]['forum_name']),"form_container");
		$form_container->output_row_header($locale['name'], array('width' => '75%'));
		$form_container->output_row_header($locale['controls'], array("class" => "align_center", 'style' => 'width: 200px', 'colspan' => 2));
		$query = dbquery("
			SELECT m.mid, m.id, m.isgroup, u.user_name, g.title
			FROM ".DB_DSB_MODERATORS." m
			LEFT JOIN ".DB_USERS." u ON (m.isgroup='0' AND m.id=u.user_id)
			LEFT JOIN ".DB_DSB_USERGROUPS." g ON (m.isgroup='1' AND m.id=g.gid)
			WHERE fid='{$fid}'
			ORDER BY m.isgroup DESC, u.user_name, g.title
		");
		while($moderator = dbarray($query))
		{
			if($moderator['isgroup'])
			{
				$moderator['img'] = "<img src=\"styles/{$page->style}/images/icons/group.gif\" alt=\"{$locale['group']}\" title=\"{$locale['group']}\" />";
				$form_container->output_cell("{$moderator['img']} <a href=\"index.php?module=user-groups&amp;action=edit&amp;gid={$moderator['id']}\">".htmlspecialchars_uni($moderator['title'])."</a>");
				$form_container->output_cell("<a href=\"index.php?module=forum-management&amp;action=editmod&amp;mid={$moderator['mid']}\">{$locale['edit']}</a>", array("class" => "align_center"));
				$form_container->output_cell("<a href=\"index.php?module=forum-management&amp;action=deletemod&amp;id={$moderator['id']}&amp;isgroup=1&amp;fid={$fid}&amp;my_post_key={$dsb->post_code}\" onclick=\"return AdminCP.deleteConfirmation(this, '{$locale['confirm_moderator_deletion']}')\">{$locale['delete']}</a>", array("class" => "align_center"));
			}
			else
			{
				$moderator['img'] = "<img src=\"styles/{$page->style}/images/icons/user.gif\" alt=\"{$locale['user']}\" title=\"{$locale['user']}\" />";
				$form_container->output_cell("{$moderator['img']} <a href=\"index.php?module=user-users&amp;action=edit&amp;uid={$moderator['id']}\">".htmlspecialchars_uni($moderator['username'])."</a>");
				$form_container->output_cell("<a href=\"index.php?module=forum-management&amp;action=editmod&amp;mid={$moderator['mid']}\">{$locale['edit']}</a>", array("class" => "align_center"));
				$form_container->output_cell("<a href=\"index.php?module=forum-management&amp;action=deletemod&amp;id={$moderator['id']}&amp;isgroup=0&amp;fid={$fid}&amp;my_post_key={$dsb->post_code}\" onclick=\"return AdminCP.deleteConfirmation(this, '{$locale['confirm_moderator_deletion']}')\">{$locale['delete']}</a>", array("class" => "align_center"));
			}
			$form_container->construct_row();
		}
		
		if($form_container->num_rows() == 0)
		{
			$form_container->output_cell($locale['no_moderators'], array('colspan' => 3));
			$form_container->construct_row();
		}
		$form_container->end();
		
		// Users
		$buttons = array();
		$form = new Form("index.php?module=forums", "post", "management");
		echo $form->generate_hidden_field("fid", $dsb->input['fid']);
		echo $form->generate_hidden_field("add", "moderators");
		$form_container = new FormContainer($locale['add_usergroup_as_moderator'],"form_container");
		$form_container->output_row($locale['usergroup']." <em>*</em>", $locale['moderator_usergroup_desc'], $form->generate_text_box('usergroup', $dsb->input['usergroup'], array('id' => 'usergroup')), 'usergroup');
		$form_container->end();
		
		// Autocompletion for usergroups
		echo '
		<script type="text/javascript" src="../jscripts/autocomplete.js?ver=1400"></script>
		<script type="text/javascript">
		<!--
			new autoComplete("usergroup", "../xmlhttp.php?action=get_usergroups", {valueSpan: "usergroup"});
		// -->
		</script>';
		
		$buttons[] = $form->generate_submit_button($locale['add_usergroup_moderator'], array("class" => "button"));
		$form->output_submit_wrapper($buttons);
		$form->end();
		echo "<br />";
		
		$form = new Form("index.php?module=forums", "post", "management");
		echo $form->generate_hidden_field("fid", $dsb->input['fid']);
		echo $form->generate_hidden_field("add", "moderators");
		$form_container = new FormContainer($locale['add_user_as_moderator'],"form_container");
		$form_container->output_row($locale['username']." <em>*</em>", $locale['moderator_username_desc'], $form->generate_text_box('username', $dsb->input['username'], array('id' => 'username')), 'username');
		$form_container->end();
		// Autocompletion for usernames
		echo '
		<script type="text/javascript" src="../jscripts/autocomplete.js?ver=1400"></script>
		<script type="text/javascript">
		<!--
			new autoComplete("username", "../xmlhttp.php?action=get_users", {valueSpan: "username"});
		// -->
		</script>';
		
		$buttons = array($form->generate_submit_button($locale['add_user_moderator'], array("class" => "button")));
		$form->output_submit_wrapper($buttons);
		$form->end();
		
		echo "</div>\n";
	}

}

/**
 *
 */
function build_admincp_forums_list(&$form_container, $pid=0, $depth=1)
{
	global $dsb, $locale, $db, $sub_forums, $aidlink;
	static $forums_by_parent;

	if(!is_array($forums_by_parent))
	{
		$forum_cache = cache_forums();

		foreach($forum_cache as $forum)
		{
			$forums_by_parent[$forum['pid']][$forum['forum_order']][$forum['fid']] = $forum;
		}
	}

	if(!is_array($forums_by_parent[$pid]))
	{
		return;
	}

	foreach($forums_by_parent[$pid] as $children)
	{
		foreach($children as $forum)
		{
			$forum['name'] = preg_replace("#&(?!\#[0-9]+;)#si", "&amp;", $forum['forum_name']); // Fix & but allow unicode
			
			if($forum['active'] == 0)
			{
				$forum['name'] = "<em>".$forum['name']."</em>";
			}
			
			if($forum['type'] == "c" && ($depth == 1 || $depth == 2))
			{
				$sub_forums = '';
				if(isset($forums_by_parent[$forum['fid']]) && $depth == 2)
				{
					build_admincp_forums_list($form_container, $forum['fid'], $depth+1);
				}
				if($sub_forums)
				{
					$sub_forums = "<br /><small>{$locale['sub_forums']}: {$sub_forums}</small>";
				}
				
				$form_container->output_cell("<div style=\"padding-left: ".(40*($depth-1))."px;\"><a href=\"index.php{$aidlink}&amp;module=forums&amp;fid={$forum['fid']}\"><strong>{$forum['name']}</strong></a>{$sub_forums}</div>");

				$form_container->output_cell("<input type=\"text\" name=\"disporder[".$forum['fid']."]\" value=\"".$forum['forum_order']."\" class=\"textbox align_center\" style=\"width: 80%; font-weight: bold;\" />", array("class" => "align_center"));
				/*
				$popup = new PopupMenu("forum_{$forum['fid']}", $locale['options']);
				$popup->add_item($locale['edit_forum'], "index.php?module=forum-management&amp;action=edit&amp;fid={$forum['fid']}");
				$popup->add_item($locale['subforums'], "index.php?module=forum-management&amp;fid={$forum['fid']}");
				$popup->add_item($locale['moderators'], "index.php?module=forum-management&amp;fid={$forum['fid']}#tab_moderators");
				$popup->add_item($locale['permissions'], "index.php?module=forum-management&amp;fid={$forum['fid']}#tab_permissions");
				$popup->add_item($locale['add_child_forum'], "index.php?module=forum-management&amp;action=add&amp;pid={$forum['fid']}");
				$popup->add_item($locale['copy_forum'], "index.php?module=forum-management&amp;action=copy&amp;fid={$forum['fid']}");
				$popup->add_item($locale['delete_forum'], "index.php?module=forum-management&amp;action=delete&amp;fid={$forum['fid']}&amp;my_post_key={$dsb->post_code}", "return AdminCP.deleteConfirmation(this, '{$locale['confirm_forum_deletion']}')");
				*/
				$form_container->output_cell(/*$popup->fetch()*/'drop_down menu cat', array("class" => "align_center"));
				
				$form_container->construct_row();
				
				// Does this category have any sub forums?
				if($forums_by_parent[$forum['fid']])
				{
					build_admincp_forums_list($form_container, $forum['fid'], $depth+1);
				}
			}
			elseif($forum['type'] == "f" && ($depth == 1 || $depth == 2))
			{
				if($forum['forum_description'])
				{
					$forum['description'] = preg_replace("#&(?!\#[0-9]+;)#si", "&amp;", $forum['forum_description']);
           			$forum['description'] = "<br /><small>".$forum['description']."</small>";
       			}
			
				$sub_forums = '';
				if(isset($forums_by_parent[$forum['fid']]) && $depth == 2)
				{
					build_admincp_forums_list($form_container, $forum['fid'], $depth+1);
				}
				if($sub_forums)
				{
					$sub_forums = "<br /><small>{$locale['sub_forums']}: {$sub_forums}</small>";
				}
					
				$form_container->output_cell("<div style=\"padding-left: ".(40*($depth-1))."px;\"><a href=\"index.php{$aidlink}&amp;module=forums&amp;fid={$forum['fid']}\">{$forum['name']}</a><br />{$forum['forum_description']}{$sub_forums}</div>");
					
				$form_container->output_cell("<input type=\"text\" name=\"disporder[".$forum['fid']."]\" value=\"".$forum['forum_order']."\" class=\"textbox align_center\" style=\"width: 80%;\" />", array("class" => "align_center"));
				/*	
				$popup = new PopupMenu("forum_{$forum['fid']}", $locale['options']);
				$popup->add_item($locale['edit_forum'], "index.php?module=forum-management&amp;action=edit&amp;fid={$forum['fid']}");
				$popup->add_item($locale['subforums'], "index.php?module=forum-management&amp;fid={$forum['fid']}");
				$popup->add_item($locale['moderators'], "index.php?module=forum-management&amp;fid={$forum['fid']}#tab_moderators");
				$popup->add_item($locale['permissions'], "index.php?module=forum-management&amp;fid={$forum['fid']}#tab_permissions");
				$popup->add_item($locale['add_child_forum'], "index.php?module=forum-management&amp;action=add&amp;pid={$forum['fid']}");
				$popup->add_item($locale['copy_forum'], "index.php?module=forum-management&amp;action=copy&amp;fid={$forum['fid']}");
				$popup->add_item($locale['delete_forum'], "index.php?module=forum-management&amp;action=delete&amp;fid={$forum['fid']}&amp;my_post_key={$dsb->post_code}", "return AdminCP.deleteConfirmation(this, '{$locale['confirm_forum_deletion']}')");
				*/
				$form_container->output_cell(/*$popup->fetch()*/'drop_down menu forum', array("class" => "align_center"));
				
				$form_container->construct_row();
				
				if(isset($forums_by_parent[$forum['fid']]) && $depth == 1)
				{
					build_admincp_forums_list($form_container, $forum['fid'], $depth+1);
				}
			}
			else if($depth == 3)
			{
				if($donecount < $dsb->settings['subforumsindex'])
				{
					$sub_forums .= "{$comma} <a href=\"index.php{$aidlink}&amp;module=forums&amp;fid={$forum['fid']}\">{$forum['name']}</a>";
					$comma = $locale['comma'];
				}
	
				// Have we reached our max visible subforums? put a nice message and break out of the loop
				++$donecount;
				if($donecount == $dsb->settings['subforumsindex'])
				{
					if(subforums_count($forums_by_parent[$pid]) > $donecount)
					{
						$sub_forums .= $comma.ds_sprintf($locale['more_subforums'], (subforums_count($forums_by_parent[$pid]) - $donecount));
						return;
					}
				}
			}
		}
	}
}

?>